/*
 * Copyright 2007 Dan Hodge
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.datajanitor.baja;

import java.util.Stack;

import net.datajanitor.baja.data.BoxFile;

class BoxFileInfoImplTree {
    private final BoxFileInfoImpl root;

    private BoxFileInfoImpl findByPath(BoxFileInfoImpl fromNode, Stack<String> pathStack) {
        BoxFileInfoImpl node = null;

        String curPath = pathStack.peek();
        if (fromNode.getName().equals(curPath)) {
            pathStack.pop();
            
            if (pathStack.isEmpty()) {
                node = fromNode;
            } else {
                for (BoxFileInfoImpl child : fromNode.getChildren()) {
                    node = findByPath(child, pathStack);
                    if (node != null) {
                        break;
                    }
                }
            }       
        }

        return node;        
    }
    
    BoxFileInfoImplTree(BoxFileInfoImpl root) {
        this.root = root;    
    }
    
    BoxFileInfoImpl getRoot() {
        return this.root;
    }
    
    BoxFileInfoImpl findById(int id) {
        return findById(this.root, id);    
    }
    
    BoxFileInfoImpl findById(BoxFileInfoImpl fromNode, int id) {
        BoxFileInfoImpl node = null;
        
        if (fromNode.getId() == id) {
            node = fromNode;
        } else {
            if (fromNode.isDirectory()) {
                for (BoxFileInfoImpl child : fromNode.getChildren()) {
                    node = findById(child, id);
                    if (node != null) {
                        break;
                    }
                }
            }
        }
        
        return node;       
    }
    
    BoxFileInfoImpl findByPath(BoxFile path) {
        if (path.isRoot()) {
            return this.root;
        } else {
            return findByPath(this.root, path);
        }
    }
    
    BoxFileInfoImpl findByPath(BoxFileInfoImpl fromNode, BoxFile path) {
        Stack<String> pathStack = new Stack<String>();
        BoxFile curPath = path;

        do {
            pathStack.push(curPath.getName());
            curPath = curPath.getParent();
        } while (curPath != null);

        if (pathStack.size() == 1) {
            return (fromNode.isRoot()) ? fromNode : null; 
        } else {
            return findByPath(fromNode, pathStack);
        }
    }
}
